Component({
  properties: {
    // 从父组件接收的数据
    productInformation: {
      type: Object,
      value: {}
    },
    selectedServiceConfigs: {
      type: Object,
      value: {}
    },
    serviceConfigs: {
      type: Array,
      value: []
    },
    address: {
      type: Object,
      value: {}
    },
    selectedTimeInfo: {
      type: Object,
      value: {}
    },
    availableTimeList: {
      type: Array,
      value: []
    },
    imgFromCheckout: {
      type: Array,
      value: []
    }
  },

  data: {
    // 组件内部数据
  },

  methods: {
    // 选择服务配置
    selectServiceConfig(e) {
      const { serviceIndex, optionIndex } = e.currentTarget.dataset;
      const { serviceConfigs, selectedServiceConfigs } = this.data;
      
      const serviceConfig = serviceConfigs[serviceIndex];
      const selectedOption = serviceConfig.options[optionIndex];
      const optionKey = `${serviceIndex}_${optionIndex}`;
      
      const newSelectedServiceConfigs = { ...selectedServiceConfigs };
      if (newSelectedServiceConfigs[optionKey]) {
        delete newSelectedServiceConfigs[optionKey];
      } else {
        newSelectedServiceConfigs[optionKey] = {
          serviceIndex,
          optionIndex,
          selectedService: selectedOption,
          quantity: 1
        };
      }
      
      // 触发父组件事件
      this.triggerEvent('serviceConfigChange', {
        selectedServiceConfigs: newSelectedServiceConfigs
      });
    },

    // 调整服务数量
    adjustServiceQuantity(e) {
      const { serviceIndex, optionIndex, action } = e.currentTarget.dataset;
      const { selectedServiceConfigs } = this.data;
      const optionKey = `${serviceIndex}_${optionIndex}`;
      const newSelectedServiceConfigs = { ...selectedServiceConfigs };
      
      if (newSelectedServiceConfigs[optionKey]) {
        const currentQuantity = newSelectedServiceConfigs[optionKey].quantity || 1;
        if (action === 'increase') {
          newSelectedServiceConfigs[optionKey].quantity = currentQuantity + 1;
        } else if (action === 'decrease' && currentQuantity > 1) {
          newSelectedServiceConfigs[optionKey].quantity = currentQuantity - 1;
        } else if (action === 'decrease' && currentQuantity === 1) {
          delete newSelectedServiceConfigs[optionKey];
        }
        
        this.triggerEvent('serviceConfigChange', {
          selectedServiceConfigs: newSelectedServiceConfigs
        });
      }
    },

    // 地址选择
    onAddressSelect() {
      this.triggerEvent('addressSelect');
    },

    // 时间选择
    onTimeSelect() {
      this.triggerEvent('timeSelect');
    },

    // 生成照片ID
    generatePhotoId() {
      const now = new Date();
      const dateString = now.toISOString().replace(/[^0-9]/g, '').slice(2, 14);
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
      return 'P' + dateString + randomNum;
    },

    // 上传照片
    async uploadPhotoWhenCheckout(e) {
      console.log("laundry-service.uploadPhotoWhenCheckout.e:", e);
      try {
        const currentCount = this.data.imgFromCheckout ? this.data.imgFromCheckout.length : 0;
        const remainingCount = 3 - currentCount;
        
        if (remainingCount <= 0) {
          wx.showToast({
            title: '最多只能上传3张图片',
            icon: 'none',
          });
          return;
        }

        const { tempFilePaths } = await wx.chooseImage({
          count: remainingCount,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
        });

        wx.showLoading({
          title: '上传中...',
          mask: true,
        });

        const uploadPromises = tempFilePaths.map((filePath, index) => {
          let fileName = this.generatePhotoId();
          const cloudPath = `checkout-photos/${fileName}.jpg`;
          return wx.cloud.uploadFile({
            cloudPath,
            filePath,
          });
        });

        const uploadResults = await Promise.all(uploadPromises);
        console.log("laundry-service.uploadPhotoWhenCheckout.res", JSON.stringify(uploadResults));
        
        const uploadedFilePaths = uploadResults.map(res => res.fileID);
        const newImgFromCheckout = [...(this.data.imgFromCheckout || []), ...uploadedFilePaths];
        
        // 触发父组件事件
        this.triggerEvent('imgFromCheckoutChange', {
          imgFromCheckout: newImgFromCheckout
        });

        wx.hideLoading();
        wx.showToast({
          title: '照片上传成功',
          icon: 'success',
        });
      } catch (err) {
        wx.hideLoading();
        console.error('上传照片失败:', err);
        wx.showToast({
          title: '照片上传失败，请重试',
          icon: 'none',
        });
      }
    },

    // 删除照片
    deletePhoto(e) {
      const { index } = e.currentTarget.dataset;
      const imgFromCheckout = [...this.data.imgFromCheckout];
      
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            imgFromCheckout.splice(index, 1);
            
            // 触发父组件事件
            this.triggerEvent('imgFromCheckoutChange', {
              imgFromCheckout: imgFromCheckout
            });
            
            wx.showToast({
              title: '删除成功',
              icon: 'success',
            });
          }
        },
      });
    },

    // 阻止事件冒泡
    preventBubble() {
      return;
    }
  }
}); 